package com.bootdo.wx.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bootdo.wx.api.ApiWeChatPayController;
import com.bootdo.wx.domain.MemberPriceDO;
import com.bootdo.wx.domain.OrderShippingDO;
import com.bootdo.wx.domain.ShopExpressCodeDO;
import com.bootdo.wx.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.wx.domain.OrderOrderDO;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 订单信息表
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-05-27 17:57:00
 */
 
@Controller
@RequestMapping("/wx/orderOrder")
public class OrderOrderController {
	@Autowired
	private OrderOrderService orderOrderService;
	@Autowired
	private ShopExpressCodeService shopExpressCodeService;
	@Autowired
	private OrderShippingService orderShippingService;
	@Autowired
	private MemberPriceService memberPriceService;
	@Autowired
	private SetWechatService setWechatService;
	@Autowired
	private WeChatPayService weChatPayService;
	
	@GetMapping()
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String OrderOrder(){
	    return "wx/orderOrder/orderOrder";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getOrderList(query);
		int total = orderOrderService.getOrderListCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:orderOrder:add")
	String add(){
	    return "wx/orderOrder/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:orderOrder:edit")
	String edit(@PathVariable("id") String id,Model model){
		OrderOrderDO orderOrder = orderOrderService.get(id);
		model.addAttribute("orderOrder", orderOrder);
	    return "wx/orderOrder/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:orderOrder:add")
	public R save( OrderOrderDO orderOrder){
		if(orderOrderService.save(orderOrder)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:orderOrder:edit")
	public R update( OrderOrderDO orderOrder){
		orderOrderService.update(orderOrder);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:remove")
	public R remove( String id){
		if(orderOrderService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
		orderOrderService.batchRemove(ids);
		return R.ok();
	}

	/*
	* 去发货
	* */
	@GetMapping("/shipments/{id}")
	@RequiresPermissions("wx:orderOrder:edit")
	String shipments(@PathVariable("id") String id,Model model){
		OrderOrderDO orderOrder = orderOrderService.get(id);
		model.addAttribute("orderOrder", orderOrder);
		List<ShopExpressCodeDO> list = shopExpressCodeService.list(new HashMap<>());
		model.addAttribute("codeList", list);
		return "wx/orderOrder/shipments";
	}

	/**
	 * 确认、修改发货
	 */
	@ResponseBody
	@PostMapping("/setShipments")
	@RequiresPermissions("wx:orderOrder:edit")
	public R setShipments( OrderOrderDO orderOrder){
		int status = orderOrder.getStatus();
		if (status != 3 && status != 4) {
			return R.error("订单状态错误");
		}
		//添加物流
		if (status == 3) {
			if(orderOrderService.addShipping(orderOrder)>0){
				return R.ok();
			}
		}
		//修改物流
		if (status == 4) {
			if(orderOrderService.editShipping(orderOrder)>0){
				return R.ok();
			}
		}
		return R.error();
	}

	/*修改收货地址*/
	@GetMapping("/editShipping/{id}")
	@RequiresPermissions("wx:orderShipping:edit")
	String editShipping(@PathVariable("id") String id,Model model){
		OrderShippingDO orderShippingDO = orderShippingService.getByOrderId(id);
		model.addAttribute("orderShipping", orderShippingDO);
		return "wx/orderShipping/edit";
	}

	/*
	* 订单详情
	* */
	@GetMapping("/orderInfo/{id}")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String orderInfo(@PathVariable("id") String id,Model model) throws ParseException{
		Map<String,Object> map = orderOrderService.getHOrderById(id);
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		if(map.get("return_at")!=null&&!"".equals(map.get("return_at").toString())){
			Date date = fmt.parse(map.get("return_at").toString());
			String s = fmt.format(date);
			map.put("return_at", s);
		}
		if(map.get("end_at")!=null&&!"".equals(map.get("end_at").toString())){
			Date date = fmt.parse(map.get("end_at").toString()); 
			String s = fmt.format(date); 
			map.put("end_at", s);
		}
		if(map.get("create_at")!=null&&!"".equals(map.get("create_at").toString())){
			Date date = fmt.parse(map.get("create_at").toString());  
			String s = fmt.format(date); 
			map.put("create_at", s);
		}
		if(map.get("consign_at")!=null&&!"".equals(map.get("consign_at").toString())){
			Date date = fmt.parse(map.get("consign_at").toString());
			String s = fmt.format(date);
			map.put("consign_at", s);
		}
		model.addAttribute("order", map);
		return "wx/orderOrder/orderInfo";
	}

	/*去统计页面*/
	@GetMapping("/statistics")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String statistics(@RequestParam Map<String, Object> params,Model model){
		model.addAttribute("map", params);
		return "wx/orderOrder/statisticsList";
	}

	/**
	 * 统计查询
	 */
	@ResponseBody
	@RequestMapping("/statisticsList")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils statisticsList(@RequestParam Map<String, Object> params){
		String status = params.get("status").toString();
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.statisticsList(query);
		int total = orderOrderService.statisticsCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/*去订单商品详情页面*/
	@GetMapping("/detailGoods/{id}")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String detailGoods(@PathVariable("id") String id,Model model){
		model.addAttribute("id",id);
		return "wx/orderOrder/detailGoods";
	}

	/**
	 * 获取订单商品详情
	 */
	@ResponseBody
	@RequestMapping("/getDetailGoods")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils getDetailGoods(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getDetailGoods(query);
		int total = orderOrderService.getDetailGoodsCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/*去砍价人员页面*/
	@GetMapping("/kUsers/{id}")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String kUsers(@PathVariable("id") String id,Model model){
		model.addAttribute("id",id);
		return "wx/orderOrder/kUsers";
	}

	/**
	 * 获取砍价人员详情
	 */
	@ResponseBody
	@RequestMapping("/getkUsers")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils getkUsers(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getKUsers(query);
		int total = orderOrderService.getKUsersCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/**
	 * 导出代发货excel表格
	 */
	@RequestMapping( "/exportExcel")
	@RequiresPermissions("wx:orderOrder:excel_out")
	public void exportExcel(@RequestParam("orderSn") String orderSn,@RequestParam("eTime") String eTime,
							@RequestParam("sTime") String sTime,@RequestParam("exports") String export,
							HttpServletResponse response,HttpServletRequest request){
		try
		{
			//1.查找代发货订单列表
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("orderSn",orderSn);
			map.put("eTime",eTime);
			map.put("sTime", sTime);
			map.put("export", export);
			map.put("status","3");
			List<Map<String,Object>> orderList = orderOrderService.getOrderList(map);
			for (Map<String,Object> orderMap : orderList) {
				List<Map<String,Object>> goodsList = orderOrderService.getDetailGoods(orderMap);
				orderMap.put("goodsList",goodsList);
			}
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("待发货订单列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			orderOrderService.exportExcel(map,orderList, outputStream,request);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 导入代发货excel表格
	 */
	@ResponseBody
	@RequestMapping( "/importExcel")
	@RequiresPermissions("wx:orderOrder:excel_in")
	public R importExcel(@RequestParam("file")MultipartFile multipartFile, HttpServletResponse response){
		/*try {
			FileUtil.multipartFileToFile(multipartFile);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		if(multipartFile!= null) {
			String userExcelFileName = multipartFile.getOriginalFilename();
			//判断是否是Excel文件
			if(userExcelFileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
			{
				orderOrderService.importExcel(multipartFile, userExcelFileName);
			}
		}
		int a = 0;
		return R.ok();
	}

	@GetMapping("/back")
	@RequiresPermissions("wx:orderOrder:back")
	String back(){
		return "wx/orderOrder/backOrder";
	}

	/*
	* 退货订单列表
	* */
	@ResponseBody
	@GetMapping("/backList")
	@RequiresPermissions("wx:orderOrder:back")
	public PageUtils backList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getBackOrderList(query);
		int total = orderOrderService.getBackOrderListCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/**
	 * 后台退货订单操作
	 */
	@PostMapping( "/backOrder")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:backOrder")
	public R backOrder(OrderOrderDO order) throws Exception {
		if (order.getStatus() == 6) {
			OrderOrderDO orderOrderDO = orderOrderService.get(order.getId());
			if (orderOrderDO.getPaytype() == 2) {  //余额支付
				//复原余额
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("gId",order.getId());
				map.put("type","0");
				MemberPriceDO memberPriceDO = memberPriceService.list(map).get(0);
				memberPriceDO.setDelFlag(1);
				memberPriceService.update(memberPriceDO);
			} else if (orderOrderDO.getPaytype() == 0) {  //微信支付
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("orderId",order.getId());
				ApiWeChatPayController apiWeChatPayController = new ApiWeChatPayController();
				try {
					return weChatPayService.refund(map);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if (orderOrderService.backOrder(order) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/*去自提订单页面*/
	@GetMapping("/postType")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	String postType(@RequestParam Map<String, Object> params,Model model){
		return "wx/orderOrder/postOrder";
	}

	/**
	 * 自提订单列表
	 */
	@ResponseBody
	@RequestMapping("/postOrderList")
	@RequiresPermissions("wx:orderOrder:orderOrder")
	public PageUtils postOrderList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> orderOrderList = orderOrderService.getOrderList(query);
		int total = orderOrderService.getOrderListCount(query);
		PageUtils pageUtils = new PageUtils(orderOrderList, total);
		return pageUtils;
	}

	/**
	 * 自提操作
	 */
	@ResponseBody
	@PostMapping("/ziTi")
	@RequiresPermissions("wx:orderOrder:edit")
	public R ziTi( OrderOrderDO orderOrder){
		String id = orderOrder.getId();
		OrderOrderDO orderDO = orderOrderService.get(id);
		if (orderDO.getStatus() != 11) {
			return R.error("该订单状态错误 ：orderDO.getStatus()");
		}
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId",orderDO.getUserId());
		paramMap.put("type","7");
		paramMap.put("orderId",id);
		if(orderOrderService.setStatusOrder(paramMap) == 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 线下支付
	 */
	@PostMapping( "/price")
	@ResponseBody
	@RequiresPermissions("wx:orderOrder:edit")
	public R price( String id){
		OrderOrderDO orderDO = orderOrderService.get(id);
		Map<String,Object> priceMap = new HashMap<String,Object>();
		priceMap.put("userId",orderDO.getUserId());
		priceMap.put("orderId",orderDO.getId());
		priceMap.put("payType", "1");
		return orderOrderService.pricePay(priceMap);
	}


}
